home *** CD-ROM | disk | FTP | other *** search
/ Language/OS - Multiplatform Resource Library / LANGUAGE OS.iso / gnu / glibc108.gz / glibc108 / glibc-1.08.1 / manual / examples / search.c < prev    next >
C/C++ Source or Header  |  1994-02-16  |  2KB  |  94 lines

  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <string.h>
  4.  
  5. /* Define an array of critters to sort. */
  6.  
  7. struct critter
  8.   {
  9.     const char *name;
  10.     const char *species;
  11.   };
  12.  
  13. struct critter muppets[] =
  14.   {
  15.     {"Kermit", "frog"},
  16.     {"Piggy", "pig"},
  17.     {"Gonzo", "whatever"},
  18.     {"Fozzie", "bear"},
  19.     {"Sam", "eagle"},
  20.     {"Robin", "frog"},
  21.     {"Animal", "animal"},
  22.     {"Camilla", "chicken"},
  23.     {"Sweetums", "monster"},
  24.     {"Dr. Strangepork", "pig"},
  25.     {"Link Hogthrob", "pig"},
  26.     {"Zoot", "human"},
  27.     {"Dr. Bunsen Honeydew", "human"},
  28.     {"Beaker", "human"},
  29.     {"Swedish Chef", "human"}
  30.   };
  31.  
  32. int count = sizeof (muppets) / sizeof (struct critter);
  33.  
  34.  
  35.  
  36. /* This is the comparison function used for sorting and searching. */
  37.  
  38. int 
  39. critter_cmp (const struct critter *c1, const struct critter *c2)
  40. {
  41.   return strcmp (c1->name, c2->name);
  42. }
  43.  
  44.  
  45. /* Print information about a critter. */
  46.  
  47. void 
  48. print_critter (const struct critter *c)
  49. {
  50.   printf ("%s, the %s\n", c->name, c->species);
  51. }
  52.  
  53.  
  54. /*@group*/
  55. /* Do the lookup into the sorted array. */
  56.  
  57. void 
  58. find_critter (const char *name)
  59. {
  60.   struct critter target, *result;
  61.   target.name = name;
  62.   result = bsearch (&target, muppets, count, sizeof (struct critter),
  63.             critter_cmp);
  64.   if (result)
  65.     print_critter (result);
  66.   else
  67.     printf ("Couldn't find %s.\n", name);
  68. }
  69. /*@end group*/
  70.  
  71. /* Main program. */
  72.  
  73. int
  74. main (void)
  75. {
  76.   int i;
  77.  
  78.   for (i = 0; i < count; i++)
  79.     print_critter (&muppets[i]);
  80.   printf ("\n");
  81.  
  82.   qsort (muppets, count, sizeof (struct critter), critter_cmp);
  83.  
  84.   for (i = 0; i < count; i++)
  85.     print_critter (&muppets[i]);
  86.   printf ("\n");
  87.  
  88.   find_critter ("Kermit");
  89.   find_critter ("Gonzo");
  90.   find_critter ("Janice");
  91.  
  92.   return 0;
  93. }
  94.